/*
 * SetUp.java
 *
 * Created on May 24, 2008, 1:08 PM
 */

package p2p.simulator.gui;

import java.awt.Color;
import java.awt.Rectangle;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import p2p.simulator.Simulator;

/**
 *
 * @author  papalukg
 */
public class SetUp extends javax.swing.JPanel {
    private Simulator S;
    private StatusBar statBar;
    private int numOfPeers;
    private int _numOfPeers;
    private int numOfKeys;
    private SimGui G;
    
    /** Creates new form SetUp */
    public SetUp() {
        initComponents();
    }
    
    public SetUp(Simulator S, StatusBar statBar, SimGui G) {
        this.S = S;
        this.G = G;
        this.statBar = statBar;
        this.numOfPeers = 0;
        this._numOfPeers = 0;
        this.numOfKeys = 0;
        
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton3 = new javax.swing.JButton();
        progressMessage = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel5 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        resetButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        peersField = new javax.swing.JTextField();
        initButton = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        keysField = new javax.swing.JTextField();

        jButton3.setText("jButton3");

        progressMessage.setFont(new java.awt.Font("Dialog", 0, 12));

        jProgressBar1.setBackground(new java.awt.Color(255, 255, 255));
        jProgressBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jProgressBar1.setBorderPainted(false);
        jProgressBar1.setPreferredSize(new java.awt.Dimension(146, 8));

        jLabel5.setText("Progress");

        jLabel3.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel3.setText("Remove all overlay nodes & statistical data");

        resetButton.setFont(new java.awt.Font("Dialog", 0, 12));
        resetButton.setText("go");
        resetButton.setIconTextGap(2);
        resetButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
        resetButton.setPreferredSize(new java.awt.Dimension(40, 24));
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });

        jLabel6.setText("Reset");

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel1.setText("Number of Cluster Peers");

        jLabel2.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel2.setText("Number of Keys");

        peersField.setColumns(8);
        peersField.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        peersField.setMinimumSize(new java.awt.Dimension(10, 10));
        peersField.setPreferredSize(new java.awt.Dimension(114, 20));

        initButton.setFont(new java.awt.Font("Dialog", 0, 12));
        initButton.setText("go");
        initButton.setIconTextGap(2);
        initButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
        initButton.setPreferredSize(new java.awt.Dimension(40, 24));
        initButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                initButtonActionPerformed(evt);
            }
        });

        jLabel7.setText("Initialize");

        jSeparator1.setForeground(new java.awt.Color(153, 166, 191));
        jSeparator1.setPreferredSize(new java.awt.Dimension(20, 4));

        jSeparator2.setForeground(new java.awt.Color(153, 166, 191));

        keysField.setColumns(8);
        keysField.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        keysField.setMinimumSize(new java.awt.Dimension(10, 10));
        keysField.setPreferredSize(new java.awt.Dimension(114, 20));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(keysField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(peersField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel7)
                    .addComponent(jLabel6)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel3))
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(progressMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)))
                    .addComponent(initButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .addComponent(resetButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(peersField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(keysField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(initButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resetButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progressMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(71, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        // TODO add your handling code here:
        int response;
        
        if (!G.isProtocolSelected()) {
            statBar.setReady(true);
            statBar.updateStatusLabel("Please select protocol...");
            
            return;
        }
        
        if ((response = confirm()) == javax.swing.JOptionPane.CANCEL_OPTION)
            return;
        
        G.protocolSelected(false);
        
        if (S.getNofPeers() == 0) {
            return;
        }
        S.exitSimulation();
        this.numOfPeers = 0;
        this.numOfKeys = 0;
        updateProgressBar(0);
}//GEN-LAST:event_resetButtonActionPerformed

    private void initButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_initButtonActionPerformed
        // TODO add your handling code here:
        
        if (!G.isProtocolSelected()) {
            statBar.setReady(true);
            statBar.updateStatusLabel("Please select protocol...");
            
            return;
        }
        try {            
            numOfPeers = Integer.parseInt(peersField.getText());
            numOfKeys = Integer.parseInt(keysField.getText());
            if (numOfPeers <= 0) {
                peersField.selectAll();
                return;
            }
            
            if (numOfKeys <= 0) {
                keysField.selectAll();
                return;
            }
        }
        catch (NumberFormatException e) {
            return;
        }
        
        statBar.updateStatusLabel("Initializing Overlay...");
        statBar.setReady(true);
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    S.initSimulator(numOfPeers, numOfKeys);
                    _numOfPeers = numOfPeers;
                    S.initOverlay(S.getProtocolPkg());
                } catch (RemoteException ex) {
                    Logger.getLogger(SetUp.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }//GEN-LAST:event_initButtonActionPerformed
    
    private int confirm() {
        
        JTextPane jTextPane1 = new JTextPane();
        jTextPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
        jTextPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jTextPane1.setEditable(false);
        jTextPane1.setPreferredSize(new java.awt.Dimension(350, 60));
        String[] initString = { "Do you realy want to reset the simulator?" };
        
        String[] initStyles = { "regular", "mail", "regular"};
        
        //JTextPane textPane = new JTextPane();
        StyledDocument doc = jTextPane1.getStyledDocument();
        addStylesToDocument(doc);
        
        try {
            for (int i=0; i < initString.length; i++) {
                doc.insertString(doc.getLength(), initString[i],
                        doc.getStyle(initStyles[i]));
            }
        } catch (BadLocationException ble) {
            System.err.println("Couldn't insert initial text into text pane.");
        }
        
         return JOptionPane.showConfirmDialog(this, jTextPane1, "Confirm reset", JOptionPane.OK_CANCEL_OPTION);
    }
    
    public void updateProgressBar (int N) {
        
        try { 
            jProgressBar1.setValue((N*100)/numOfPeers);
        } catch (java.lang.ArithmeticException e) {
            jProgressBar1.setValue(0);
        }
        
        Rectangle progressRect = jProgressBar1.getBounds();
        progressRect.x = 0;
        progressRect.y = 0;
        jProgressBar1.paintImmediately(progressRect);
        
        if (N == numOfPeers) {
            statBar.updateStatusLabel("Done");
            statBar.setReady(false);
        }
        
    }
    
    public int getNumOfNodes () {
        return _numOfPeers;
    }
    
    protected void addStylesToDocument(StyledDocument doc) {
        //Initialize some styles.
        Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

        Style regular = doc.addStyle("regular", def);
        StyleConstants.setFontFamily(def, "Dialog");
        StyleConstants.setFontSize(regular, 12);
        StyleConstants.setForeground(def, new Color(51,51,51));
        
        StyleConstants.setAlignment(regular, StyleConstants.ALIGN_JUSTIFIED);
        doc.setParagraphAttributes(0, doc.getLength(), regular, false);
        
        Style s = doc.addStyle("italic", regular);
        StyleConstants.setItalic(s, true);

        s = doc.addStyle("bold", regular);
        StyleConstants.setBold(s, true);

        s = doc.addStyle("small", regular);
        StyleConstants.setFontSize(s, 10);

        s = doc.addStyle("large", regular);
        StyleConstants.setFontSize(s, 16);
        
        s = doc.addStyle("mail", regular);
        StyleConstants.setForeground(s, Color.BLUE);
        
        /*s = doc.addStyle("icon", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        ImageIcon pigIcon = createImageIcon("images/Pig.gif", "a cute pig");
      
        if (pigIcon != null) {
            StyleConstants.setIcon(s, pigIcon);
        }

        s = doc.addStyle("button", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        ImageIcon soundIcon = createImageIcon("images/sound.gif",
                                              "sound icon");
        JButton button = new JButton();
        if (soundIcon != null) {
            button.setIcon(soundIcon);
        } else {
            button.setText("BEEP");
        }
        button.setCursor(Cursor.getDefaultCursor());
        button.setMargin(new Insets(0,0,0,0));
        button.setActionCommand(buttonString);
        button.addActionListener(this);
        StyleConstants.setComponent(s, button);
         */
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton initButton;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextField keysField;
    private javax.swing.JTextField peersField;
    private javax.swing.JLabel progressMessage;
    private javax.swing.JButton resetButton;
    // End of variables declaration//GEN-END:variables
    
}
